import {createRouter,createWebHistory} from 'vue-router'

import Layout from "../views/Layout/Layout";
import store from '../store/store'


const _import = require('@/router/_import')//获取组件的方法

const history = createWebHistory();

const router = createRouter({
    history : history,
    routes:[
        {
            path:'/',
            component:()=>import('../views/Main.vue'),
            name: '首页',
            meta:{
                NoNeedHome: false // 添加该字段，表示需要home模板
            },
            children:[]
        },
        {
            path:'/login',
            component:()=>import('../views/login.vue'),
            name:'登录',
            meta:{
                requireAuth:true,// 不做登录校验
                NoNeedHome: true // 添加该字段，表示不需要home模板
            }
        },
        {
            path:'/404',
            name:'404',
            component:()=>import('../views/404.vue')
        }
    ]
});

// 页面刷新时，重新赋值token 
if (sessionStorage.getItem('token')) { 
    store.commit('setToken', sessionStorage.getItem('token')) 
} 

/**
 * 路由拦截器
 */
router.beforeEach((to,from,next)=>{
    const token = store.state.token;

    if(to.matched.some(record=>record.meta.requireAuth || record.meta.homePages)){
        //路由元信息requireAuth:true 或者homePages:true，则不做登录校验
        next()
    }
    else{
        //判断用户是否登录
        if(token){
            //判断路由来源是否有query，处理不是目的跳转的情况
            if(Object.keys(from.query).length === 0){
                next();
            }else{
                let redirect = from.query.redirect//如果来源路由有query
                if(to.path === redirect){//这行是解决next无限循环的问题
                    next()
                }else{
                    next({path:redirect})//跳转到目的路由
                }
            }
        }else{//没登陆，跳转志登录页面
            if(to.path==="/login"){
                next()
            }else{
                next({
                      path:"/login",
                      query: {redirect: to.fullPath}//将目的路由地址存入login的query中
                })
            }
        }
    }
})

export function filterAsyncRouter(asyncRouterMap) {
    //注意这里的 asyncRouterMap 是一个数组
    const accessedRouters = asyncRouterMap.filter(route => {
        if (route.path && !route.IsButton) {
            if (route.path === '/' || route.path === '-') {//Layout组件特殊处理
                route.component = Layout;
                route.path = '/'
            } else {
                try {
                    route.path = route.path.replace('/:id','')
                    route.component = _import(route.path.replace('/:id',''))
                } catch (e) {
                    try {
                        route.component = () => import('@/views' + route.path.replace('/:id','') + '.vue');
                    } catch (error) {
                        console.info('%c 当前路由 ' + route.path.replace('/:id','') + '.vue 不存在，因此如法导入组件，请检查接口数据和组件是否匹配，并重新登录，清空缓存!', "color:red")
                    }
                }
            }
        }
        if (route.children && route.children.length && !route.IsButton) {
            route.children = filterAsyncRouter(route.children)
        }
        return true
    })

    return accessedRouters
}
/*
export function filterAsyncRouter(asyncRouterMap) {
    //注意这里的 asyncRouterMap 是一个数组
    const accessedRouters = asyncRouterMap.filter(route => {
        if (route.path && !route.IsButton) {
            if (route.path.replace(/\s+/g,"") === '/' || route.path.replace(/\s+/g,"") === '-') {//Layout组件特殊处理
                route.component = Layout
                route.path = '/'
                //route.component = () => import('@/views/404.vue');
            } else {
                try {
                    route.path = route.path.replace('/:id','')
                    route.component = _import(route.path.replace('/:id',''))
                } catch (e) {
                    try {
                        route.component = () => import('@/views' + route.path.replace('/:id','') + '.vue');
                    } catch (error) {
                        console.info('%c 当前路由 ' + route.path.replace('/:id','') + '.vue 不存在，因此如法导入组件，请检查接口数据和组件是否匹配，并重新登录，清空缓存!', "color:red")
                    }
                }
            }
        }
        if (route.children !== null && !route.IsButton) {
            route.children = filterAsyncRouter(route.children)
        }
        return true
    })

    return accessedRouters
}
*/

router.$addRoutes = (params) => {

    var f = item => {
        
        if (item['children']) {
            item['children'] = item['children'].filter(f);
            return true;
        } else if (item['IsButton']) {
            return item['IsButton']===false;
        }  else {
            return true;
        }
        
    }
    
    var paras = params.filter(f);

    router.addRoute(paras,'首页');
    paras.forEach((route)=>{
        router.addRoute(route,paras.name);
        router.options.routes.push(route)
    })
}

export default router;


export function getAsyncRoutes(routes){
    const res = []

    routes.forEach(route=>{
        if(route.children !== null){
            //const children = []

            route.children.forEach(menu=>{
                res.push({
                    path:menu.path,
                    name:menu.meta.title,
                    component:(resolve)=>require([`@/views${menu.path}`],resolve),
                    meta:{
                        title:menu.meta.title
                    }
                })

            })
            
            //res.push({
              //  path:route.path,
              //  component:Layout,
              //  children:children
            //})
            
        }
    })

    return res;
}
